package com.itshare.video.common.util;

import org.springframework.context.annotation.Lazy;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;

import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Valid;
import javax.validation.Validator;
import java.util.Set;

/**
 * @Author lyr
 * @create 2020/11/10 23:07
 */
@Component
@Lazy
public class ValidateUtils {
    @Resource
    Validator validator;

    public void doValidate(MethodParameter parameter,Object bean) {
        if (parameter.hasParameterAnnotation(Valid.class) ||
        parameter.hasParameterAnnotation(Validated.class)) {
            Set<ConstraintViolation<Object>> res = validator.validate(bean);
            if (res.size()>0) {
                throw new ConstraintViolationException(res);
            }
        }

    }
}
